package ge.unihack.instantdj.protocol.common;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.json.JSONException;
import org.json.JSONObject;

public class JSONCommandReader implements CommandReader {

	@Override
	public Command readCommand(InputStream in) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(in));
		String commandData = br.readLine();
		if (commandData == null) {
			return null;
		}
		try {
			JSONObject json = new JSONObject(commandData.toString());
			Command command = new Command();
			command.setType(Command.Type.valueOf(json.getString("type")));
			return command;
		} catch (JSONException e) {
			throw new IOException("Error while reading JSONCommand: " + e.toString());
		}
	}

}
